package services

import (
	"github.com/mlogclub/simple/common/strs"
	"github.com/mlogclub/simple/sqls"
	"github.com/mlogclub/simple/web/params"

	"bbs-go/internal/models"
	"bbs-go/internal/repositories"
)

var ApprovalTemplateService = newApprovalTemplateService()

func newApprovalTemplateService() *approvalTemplateService {
	return &approvalTemplateService{}
}

type approvalTemplateService struct {
}

func (s *approvalTemplateService) Get(id int64) *models.ApprovalTemplate {
	return repositories.ApprovalTemplateRepository.Get(sqls.DB(), id)
}

func (s *approvalTemplateService) Take(where ...interface{}) *models.ApprovalTemplate {
	return repositories.ApprovalTemplateRepository.Take(sqls.DB(), where...)
}

func (s *approvalTemplateService) Find(cnd *sqls.Cnd) []models.ApprovalTemplate {
	return repositories.ApprovalTemplateRepository.Find(sqls.DB(), cnd)
}

func (s *approvalTemplateService) FindPageByParams(params *params.QueryParams) (list []models.ApprovalTemplate, paging *sqls.Paging) {
	return repositories.ApprovalTemplateRepository.FindPageByParams(sqls.DB(), params)
}

func (s *approvalTemplateService) FindPageByCnd(cnd *sqls.Cnd) (list []models.ApprovalTemplate, paging *sqls.Paging) {
	return repositories.ApprovalTemplateRepository.FindPageByCnd(sqls.DB(), cnd)
}

func (s *approvalTemplateService) Create(t *models.ApprovalTemplate) error {
	return repositories.ApprovalTemplateRepository.Create(sqls.DB(), t)
}

func (s *approvalTemplateService) Update(t *models.ApprovalTemplate) error {
	return repositories.ApprovalTemplateRepository.Update(sqls.DB(), t)
}

func (s *approvalTemplateService) Updates(id int64, columns map[string]interface{}) error {
	return repositories.ApprovalTemplateRepository.Updates(sqls.DB(), id, columns)
}

func (s *approvalTemplateService) UpdateColumn(id int64, name string, value interface{}) error {
	return repositories.ApprovalTemplateRepository.UpdateColumn(sqls.DB(), id, name, value)
}

func (s *approvalTemplateService) CreateApprovalTemplate(req *models.CreateApprovalTemplateRequest) error {
	tx := sqls.DB().Begin()

	approvalTemplate := models.ApprovalTemplate{
		Code: strs.UUID(),
		Name: req.Name,
	}
	err := repositories.ApprovalTemplateRepository.Create(tx, &approvalTemplate)
	if err != nil {
		tx.Rollback()
		return err
	}

	for _, node := range req.Nodes {
		err = repositories.ApprovalTemplateNodesRepository.Create(tx, &models.ApprovalTemplateNodes{
			Name:           node.Name,
			TemplateId:     int(approvalTemplate.Id),
			Sort:           node.Sort,
			ApprovalUserId: node.ApprovalUserId,
		})

		if err != nil {
			tx.Rollback()
			return err
		}
	}

	err = tx.Commit().Error
	if err != nil {
		tx.Rollback()
		return err
	}

	return nil
}
